//
//  NSString+KR.m
//  KEREN
//
//  Created by MW on 2023/3/21.
//

#import "NSString+KR.h"

@implementation NSString (KR)
+ (NSString *)setPassWord:(NSString *)str{
    NSString *numPattern = @".*\\d+.*";
    NSString *lowerPattern = @".*[a-z]+.*";
    NSString *upperPattern = @".*[A-Z]+.*";
    NSString *regex = @"[~`!@#$%^&*()_+-=[]|{};；‘。，！¥':\",./<>?]{,}/";
    
    NSPredicate *numPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numPattern];
    NSPredicate *lowerPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", lowerPattern];
    NSPredicate *upperPred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", upperPattern];

    if(str.length > 16){
        str =  [str substringToIndex:16];
    }
    for (int i = 0; i<str.length; i++){
        NSString *string = [str substringWithRange:NSMakeRange(i, 1)];
        if (![numPred evaluateWithObject:string] && ![upperPred evaluateWithObject:string] && ![lowerPred evaluateWithObject:string] && ![regex containsString:string]) {
            str =  [str stringByReplacingOccurrencesOfString:string withString:@""];
            break;
        }
    }
    return str;
}

-(NSData *)hexStringToData{
    const char* ch = [[self lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];
    while (*ch) {
        if (*ch == ' ') {
            continue;
        }
        char byte = 0;
        if ('0' <= *ch && *ch <= '9') {
            byte = *ch - '0';
        }else if ('a' <= *ch && *ch <= 'f') {
            byte = *ch - 'a' + 10;
        }else if ('A' <= *ch && *ch <= 'F') {
            byte = *ch - 'A' + 10;
        }
        ch++;
        byte = byte << 4;
        if (*ch) {
            if ('0' <= *ch && *ch <= '9') {
                byte += *ch - '0';
            } else if ('a' <= *ch && *ch <= 'f') {
                byte += *ch - 'a' + 10;
            }else if('A' <= *ch && *ch <= 'F'){
                byte += *ch - 'A' + 10;
            }
            ch++;
        }
        [data appendBytes:&byte length:1];
    }
    return data;
}
@end
